<script setup lang="ts">
    import { reactive, ref, onMounted, watch } from 'vue'//引入vue函数
    import { uploadPictureURL } from '@/api' //引入API函数
    import { useToken } from '@/stores/token' //导入token状态文件
    import { getCategoryList, addGoods, updateGoods } from '@/api' //数据接口
    import type { AxiosResponse } from 'axios' //导入response类型
    import type { FormInstance, UploadInstance } from 'element-plus' //导入实例类型
    import type { Category } from '@/model' //导入自定义数据类型
    import { ElMessage } from 'element-plus' //导入消息框
    import CKEditor from './CKEditor.vue' //导入CKEditor编辑器组件

    //自定义事件
    const emit = defineEmits(["closeDialog"])

    //获得当前组件属性
    const props = defineProps(["isShow", "goods"])

    //执行方法获得tokenStore对象
    const tokenStore = useToken()

    //图片上传地址
    const uploadURL = uploadPictureURL()

    //设置上传时请求的头
    const headers = { jwt: tokenStore.token }

    //定义表单数据对象
    const formObj = reactive({
        name:"",
        category_id:"",
        price:"",
        picture:"",
        stock:"",
        spec:"",
        description:""
    });

    //定义表单对象实例的引用
    const formRef = ref<FormInstance>()

    //定义商品上传组件实例
    const uploadRef = ref<UploadInstance>()

    //定义商品上传组件中，已上传文件列表
    const fileList = ref()

    //下拉框商品分类数据
    const categoryList = ref<Category[]>()

    //定义表单验证规则
    const rules = reactive({
        name:[
            { required:true, message:"商品名称不能为空", trigger:"blur" }
        ],
        category_id:[
            { required:true, message:"分类名称不能为空", trigger:"blur" }
        ],
        price:[
            { required:true, message:"商品价格不能为空", trigger:"blur" },
            { type:"number", message:"商品价格必须是数字类型", trigger:"blur" }
        ],
        picture:[
            { required:true, message:"商品图片不能为空", trigger:"blur" }
        ],
        stock:[
            { required:true, message:"商品库存不能为空", trigger:"blur" },
            { type:"number", message:"商品库存必须是数字类型", trigger:"blur" }
        ],
        spec:[
            { required:true, message:"商品规格不能为空", trigger:"blur" }
        ],
        description:[
            { required:true, message:"商品简介不能为空", trigger:"blur" }
        ]
    })

    //表单提交，添加或修改商品
    async function submitForm(){
        await formRef.value?.validate(async (valid, _fields)=>{
            if(valid){
                var res = null
                if(props.goods.id == 0){
                    //添加商品
                    res = await addGoods(formObj)
                }
                else{
                    //修改分类
                    const data = {
                        id:props.goods.id,
                        name:formObj.name,
                        category_id:formObj.category_id,
                        price:formObj.price,
                        picture:formObj.picture.substring(formObj.picture.lastIndexOf("static")),
                        stock:formObj.stock,
                        spec:formObj.spec,
                        description:formObj.description,
                        album:[]
                    }
                    res = await updateGoods(data)
                }
                if(res.data.errno == 0){
                    //发送自定义事件
                    emit("closeDialog")
                    //添加或修改成功
                    ElMessage.success(res.data.errmsg)
                }
                else{
                    //添加或修改失败
                    ElMessage.error(res.data.errmsg)
                }
            }
        })
    }

    //图片上传成功后的回调函数
    function uploadSuccess(response:AxiosResponse){
        //设置将要提交的商品图片
        formObj.picture = response.data.savepath
    }

    //商品图片列表文件被移除的回调函数
    function removeSuccess(){
        formObj.picture = ""
    }

    //查询所有商品分类
    async function loadCategoryList(){
        const res = await getCategoryList()
        convertToTree(res.data.data)
    }

    //将数据转换为树状数据
    function convertToTree(data:Category[]){
        //处理数据
        var newData:Category[] = []
        //获得所有一级分类
        data.forEach((v)=>{
            if(v.pid == 0){
                newData.push(v)
            }
        })
        //获得二级分类
        newData.forEach((v)=>{
            const result = data.filter((item)=>item.pid==v.id)
            v.children = result
        })
        //返回结果
        categoryList.value = newData
    }

    //初始化表单数据
    function initForm(){
        //设置表单数据
        if(props.goods.id != 0){
            formObj.name = props.goods.name
            formObj.category_id = props.goods.category_id
            formObj.price = props.goods.price
            formObj.picture = props.goods.picture
            formObj.stock = props.goods.stock
            formObj.spec = props.goods.spec
            formObj.description = props.goods.description
            //设置商品图片上传组件中，已上传图片的列表
            fileList.value = [
                {
                    name:props.goods.picture.substring(props.goods.picture.lastIndexOf('/') + 1),
                    url:props.goods.picture
                }
            ]
        }
        else{
            //清空表单
            formObj.name = ""
            formObj.category_id = ""
            formObj.price = ""
            formObj.picture = ""
            formObj.stock = ""
            formObj.spec = ""
            formObj.description = ""
            //清空上传组件的已上传文件列表
            uploadRef.value?.clearFiles()
        }
    }

    //监听当前组件属性是否发生变化
    watch(props,()=>{
        //重置表单
        //resetForm()
        //初始化表单数据
        initForm()
    })

    //组件加载完成
    onMounted(()=>{
        //查询所有商品分类
        loadCategoryList()
        //初始化表单数据
        initForm()
    })
</script>

<template>
    <el-form ref="formRef" :model="formObj" :rules="rules" label-width="120" status-icon>
        <el-form-item label="商品名称" prop="name">
            <el-input v-model="formObj.name" placeholder="请填写商品名称" style="width:500px;"></el-input>
        </el-form-item>
        <el-form-item label="分类名称" prop="category_id">
            <el-select v-model="formObj.category_id" placeholder="请选择二级分类名称" style="width:200px;">
                <el-option-group v-for="group in categoryList" :label="group.name">
                    <el-option v-for="item in group.children" :label="item.name" :value="item.id"></el-option>
                </el-option-group>
            </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
            <!--注：v-model必须加number，将文本值转为数字；否则表单验证无法通过-->
            <el-input v-model.number="formObj.price" placeholder="请填写商品价格" style="width:500px;"></el-input>
        </el-form-item>
        <el-form-item label="商品图片" prop="picture">
            <el-upload ref="uploadRef" :action="uploadURL" v-model:file-list="fileList" :limit="1" :headers="headers" :data="{type:'goods'}" :on-success="uploadSuccess" :on-remove="removeSuccess">
                <template #trigger>
                    <el-button type="primary">选择图片</el-button>
                </template>
                <template #tip>
                    <div class="upload_tooltip">图片文件大小不超过500KB</div>
                </template>
            </el-upload>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
            <!--注：v-model必须加number，将文本值转为数字；否则表单验证无法通过-->
            <el-input v-model.number="formObj.stock" placeholder="请填写库存数量" style="width:500px;"></el-input>
        </el-form-item>
        <el-form-item label="商品规格" prop="spec">
            <el-input v-model="formObj.spec" placeholder="请填写商品规格" style="width:500px;"></el-input>
        </el-form-item>
        <el-form-item label="商品简介" prop="description">
            <div class="editor-box"><CKEditor v-model="formObj.description"></CKEditor></div>
        </el-form-item>
        <el-form-item label="">
            <el-button type="primary" @click="submitForm">{{ props.goods.id==0?"新增":"修改" }}</el-button>
            <el-button @click="initForm">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<style scoped>
    .upload_tooltip{
        font-size:13px;
        color:#A8ABB2;
    }
    .editor-box{
        width:500px;
    }
</style>